<template>
    <div class="content-wrap">
        <div class="content-top-box" v-if="addBtn">
            <!-- 搜索区域 -->
            <ul class="search-container">
                <li>
                    <el-button class="search-btn" type="primary" icon="el-icon-plus" @click="addFn">新增</el-button>
                </li>
            </ul>
        </div>

        <div class="content-bottom-box">
            <!-- 表格 -->
            <div class="content-form-box">
                <el-table
                    v-loading="loadingFlag"
                    :data="tableData"
                    :height="tableHeight"
                    ref="table"
                    border
                    stripe
                    style="width: 100%"
                >
                    <el-table-column
                        prop="serialNumber"
                        label="序号"
                        width="60"
                        :show-overflow-tooltip="true"
                        fixed
                        >
                    </el-table-column>
                    <el-table-column
                        prop="name"
                        label="角色"
                        width="300"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="creator"
                        label="创建人"
                        :show-overflow-tooltip="true"
                        width="300"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="createTime"
                        label="创建时间"
                        :show-overflow-tooltip="true"
                        width="300"
                        >
                    </el-table-column>
                    <el-table-column
                        label="状态"
                        width="120"
                        :show-overflow-tooltip="true"
                        >
                        <template slot-scope="scope">
                            <span>{{scope.row.enabled ? '启用' : '禁用'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        fixed="right">
                        <template slot-scope="scope">
                            <el-button @click="authorityInfoFn(scope.row.id, scope.row.name)" type="text" size="small" v-if="authBtn">权限配置</el-button>
                            <el-button @click="editInfoFn(scope.row.id)" type="text" size="small" v-if="editBtn">编辑</el-button>
                            <el-button @click="deleteInfoFn(scope.row.id, scope.row.name)" type="text" size="small" v-if="deleteBtn">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 页码 -->
            <div class="content-Page-container">
                <BaseFormPage 
                    :pagination="pagination"
                    @cFirstPageFn="cFirstPageFn"
                    @cLastPageFn="cLastPageFn"
                    @cJumpPageFn="cJumpPageFn"
                    @cPreFn="cPreFn"
                    @cNextFn="cNextFn"
                    @cRefreshFn="cRefreshFn"
                    >
                </BaseFormPage>
            </div>
        </div>

        <!-- 新增/编辑提示 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFlag"
            width="344px"
            :show-close="false"
            center
            class="role-dialog-content">
            <div class="dialog-wrap">
                <el-form 
                    :model="ruleForm" 
                    :rules="rules" 
                    ref="ruleForm" 
                    :hide-required-asterisk="true"
                    label-width="60px" 
                    class="form-box"
                >
                    <el-form-item label="角色：" prop="roleName">
                        <el-input 
                            v-model="ruleForm.roleName" 
                            placeholder="请输入角色" 
                            maxlength="20"
                            show-word-limit>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="状态：" prop="state">
                        <el-select v-model="ruleForm.state" placeholder="请选择">
                            <el-option label="启用" value="1"></el-option>
                            <el-option label="禁用" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="resetForm('ruleForm')">取 消</el-button>
                <el-button size="small" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除提示 -->
        <el-dialog
            title="删除"
            :visible.sync="delDialogFlag"
            width="340px"
            :show-close="false"
            top="30vh"
            center
            class="role-delete-wrap">
            <span>请确认是否删除角色：<i class="color-primary">{{currentName}}</i> ？</span>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="cancelDeleteFn">取 消</el-button>
                <el-button size="small" type="primary" @click="deleteRoleFn">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Storage from "@/utils/storage";
import BaseFormPage from '@/components/BaseFormPage';
export default {
    components: {
        BaseFormPage
    },
    data() {
        return {
            loadingFlag: false,         //表格数据加载状态
            dialogFlag: false,          //弹窗显示状态
            delDialogFlag: false,       //删除弹窗显示状态

            pageIndex: 1,
            pageSize: 20,
            tableHeight: 200,           //表格初始高度
            tableData: [],              //表格数据
            pagination: {               //分页数据
                loadingFlag: false,     //数据加载状态
                currentPage: 1,         //当前页
                totalPage: 1,           //总页数
                totalNum: 0,            //总条数
                firstNum: 0,            //分页显示起始值
                endNum: 0               //分页显示结束值
            },

            dialogTitle: '',
            isEditFlag: false,
            currentEditId: '',
            currentName: '',
            currentDelId: '',

            ruleForm: {
                roleName: '',
                state: '',
            },
            rules: {
                roleName: [
                    { required: true, message: '请输入角色', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                state: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                ],
            },

            addBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(285) == -1 ? false : true,
            authBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(294) == -1 ? false : true,
            editBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(286) == -1 ? false : true,
            deleteBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(287) == -1 ? false : true,
        }
    },
    created() {
        this.getListData()
    },
    methods: {
        getListData() {
            this.loadingFlag = true;
            this.pagination.loadingFlag = true;
            let params = {
                pgCt: this.pageIndex,
                pgSz: this.pageSize
            }

            this.$http.post('/role/list', params)
                .then((res) => {
                    if(res.data.records.length > 0) {
                        this.pagination.totalPage = res.data.pages
                        this.pagination.totalNum = res.data.total
                        
                        res.data.records.forEach((item, index) => {
                            //列表下标
                            item.index = index
                            //列表序号
                            item.serialNumber = ((this.pageIndex - 1) * this.pageSize) + (index + 1)
                        })
                        this.pagination.firstNum = res.data.records[0].serialNumber
                        this.pagination.endNum = res.data.records[res.data.records.length-1].serialNumber
                    }else{
                        this.pagination.currentPage = 1
                        this.pagination.totalPage = 1
                        this.pagination.totalNum = 0
                        this.pagination.firstNum = 0
                        this.pagination.endNum = 0
                    }
                    this.tableData  = res.data.records;
                }).then(() => {
                    this.tableHeightFn();
                    this.loadingFlag = false;
                    this.pagination.loadingFlag = false;
                })
        },
        tableHeightFn() { //表格高度
            let tableDataLength = this.tableData.length;
            let minHeight = tableDataLength == 0 ? 0 : 80;
            this.$nextTick(function () {
                this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - minHeight;
                if(this.tableData.length <= 0) {
                    this.tableHeight = '60vh'
                }
                
                let self = this;
                window.onresize = function() {
                    self.tableHeight = window.innerHeight - self.$refs.table.$el.offsetTop - minHeight;
                    self.tableHeight = self.tableHeight < 200 ? 200 : self.tableHeight;
                }
            })
        },
        resetPageIndex() { //重置页码
            this.pagination.currentPage = 1;
            this.pageIndex = 1;
        },
        searchFn() { //搜索
            this.resetPageIndex()
            this.getListData()
        },
        addFn() { //新增
            console.log('addFn')
            this.dialogTitle = '新增'
            this.dialogFlag = true
            this.isEditFlag = false
        },
        changeState() { //选择状态
            this.resetPageIndex()
            this.getListData()
        },

        authorityInfoFn(id, name) {
            console.log('authorityInfoFn:', id)
            this.$router.push({
                name: 'roleOperate',
                query: {
                    roleId: id,
                    roleName: name
                }
            })
        },

        editInfoFn(id) { //编辑
            console.log('currentid:', id)
            this.dialogTitle = '编辑'
            this.dialogFlag = true
            this.isEditFlag = true
            this.currentEditId = id
            this.getDetailFn(id)
        },
        getDetailFn(id) {
            this.$http.get('/role/getRoleById/' + id)
                .then((res) => {
                    this.ruleForm.roleName = res.data.name
                    this.ruleForm.state = res.data.enabled ? '1' : '0'
                })
        },
        submitForm(formName) { //确认提交
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.addOrEditRoleFn()
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        addOrEditRoleFn() {
            let params = {
                id: this.currentEditId,
                name: this.ruleForm.roleName,
                enabled: this.ruleForm.state,
                creator: Storage.get('name') || '',
            }
            if(this.isEditFlag) {
                delete params.creator
            }else{
                delete params.id
            }

            console.log('params:', JSON.stringify(params))
            // return

            this.$http.post('/role/addOrUpdate', params)
                .then((res) => {
                    this.dialogFlag = false;
                    this.$message({
                        message: this.isEditFlag ? '编辑成功' : '新增成功',
                        type: 'success'
                    });
                    this.resetForm('ruleForm');
                    setTimeout(() => {
                        this.searchFn()
                    }, 1000)
                })
        },
        resetForm(formName) { //重置表单内容
            this.$refs[formName].resetFields();
            this.dialogFlag = false;
        },
        deleteInfoFn(id, name) { //删除
            console.log('删除:', id)
            this.delDialogFlag = true;
            this.currentDelId = id;
            this.currentName = name;
        },
        deleteRoleFn() {
            this.$http.get('/role/deleteRole/' + this.currentDelId)
                .then((res) => {
                    this.delDialogFlag = false
                    this.$message({
                        message: '已删除',
                        type: 'success'
                    });
                    setTimeout(() => {
                        this.searchFn()
                    }, 1000)
                })
        },
        cancelDeleteFn() {
            this.delDialogFlag = false
            this.currentName = ''
            this.currentDelId = ''
        },

        cFirstPageFn(pageNum) { //首页
            this.pageIndex = pageNum;
            this.getListData()
        },
        cLastPageFn(pageNum) { //尾页
            this.pageIndex = pageNum;
            this.getListData()
        },
        cJumpPageFn(pageNum) { //页码跳转
            this.pageIndex = pageNum;
            this.getListData()
        },
        cPreFn(pageNum) { //上一页
            this.pageIndex = pageNum;
            this.getListData()
        },
        cNextFn(pageNum) { //下一页
            this.pageIndex = pageNum;
            this.getListData()
        },
        resetParams() { //重置参数
            this.tableData = []
            this.pageIndex = 1
            this.pageSize = 20
            this.pagination = {
                loadingFlag: false,
                currentPage: 1,
                totalPage: 1,
                totalNum: 0,
                firstNum: 0,
                endNum: 0
            }
        },
        cRefreshFn() { //刷新
            this.resetParams()
            this.getListData()
        }
    }
}
</script>

<style lang="scss" scoped>

</style>

<style lang="scss">
    .role-dialog-content {
        .dialog-wrap {
            .el-select {
                width: 100%;
            }
        }
        .el-dialog__footer {
            .el-button+.el-button {
                margin-left: 50px;
            }
        }
    }

    .role-delete-wrap {
        .el-dialog__header {
            padding: 18px 20px;
        }
        .el-dialog__body {
            padding-bottom: 24px;
            text-align: center;
        }
        .el-dialog__footer {
            .el-button+.el-button {
                margin-left: 50px;
            }
        }
    }
</style>